#include <iostream>
#include <unistd.h>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(const std::string proc)
{
    std::cout << "\n\tUsage: " << proc << " port[1024+]\n"
              << std::endl;
}

// ./tcpclient.cc serverip serverport
int main(int argc, char *argv[])
{
    // 使用手册
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    // 拿到命令行中的IP地址和端口号
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 初始化
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));
    socklen_t len = sizeof(server);

    while (true)
    {
        int cnt = 5;
        bool isreconnect = false;
        // sockfd
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            exit(2);
        }
        // std::cerr << "socket success" << std::endl;
        // bind问题:这里和udp套接字一样，不需要手动绑定，是OS自动给我们绑定，客户端这里只要保证端口号不一样即可

        do
        {
            // connect链接
            int n = connect(sockfd, (struct sockaddr *)&server, len);
            if (n < 0)
            {
                isreconnect = true;
                cnt--;
                std::cerr << "connect error,cnt:" << cnt << std::endl;
                sleep(2);
            }
            else
            {
                break;
            }
        } while (cnt && isreconnect);

        if (cnt == 0)
        {
            std::cerr << "user offonline" << std::endl;
            break;
        }

        std::cerr << "connect success" << std::endl;

        std::string message;
        std::cout << "Please enter#";
        // 获取输入
        getline(std::cin, message);

        // 向sockfd中写入
        int m = write(sockfd, message.c_str(), message.size());
        if (m < 0)
        {
            std::cerr << "write error..." << std::endl;
            continue;
        }
        // 从sockfd中读取
        char buffer[4096];
        int n = read(sockfd, buffer, sizeof(buffer));
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }

        // 关闭sockfd
        close(sockfd);
    }
    return 0;
}